#include <windows.h>
#include <commctrl.h>
#include <tchar.h>
#include <SDKDDKVer.h>

#include "Globals.h"
#include "MainWindow.h"
#include "Resource.h"
#include "Star.h"
#include "time.h"

/* Global instance handle */
HINSTANCE g_hInstance = NULL;
HWND hWnd;

void draw_pixel(int x, int y, unsigned int rgb) {
  HDC hdc = GetDC(hWnd);
  HBRUSH brush = (HBRUSH)GetStockObject(BLACK_BRUSH);
  RECT rect = {x, y, x, y};
  FillRect(hdc, &rect, brush);
  DeleteObject(brush);
  ReleaseDC(hWnd, hdc);
}

void fill_rect(int x0, int y0, int x1, int y1, unsigned int rgb) {
  HDC hdc = GetDC(hWnd);
  HBRUSH brush = (HBRUSH)CreateSolidBrush(RGB(
      ((((unsigned int)(rgb)) >> 16) & 0xFF),
      ((((unsigned int)(rgb)) >> 8) & 0xFF), (((unsigned int)(rgb)) & 0xFF)));
  RECT rect = {x0, y0, x1, y1};
  FillRect(hdc, &rect, brush);
  DeleteObject(brush);
  ReleaseDC(hWnd, hdc);
}

/* Our application entry point */
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine, int nCmdShow) {
  INITCOMMONCONTROLSEX icc;
  HACCEL hAccelerators;
  MSG msg;

  /* Assign global HINSTANCE */
  g_hInstance = hInstance;

  /* Initialise common controls */
  icc.dwSize = sizeof(icc);
  icc.dwICC = ICC_WIN95_CLASSES;
  InitCommonControlsEx(&icc);

  /* Register our main window class, or error */
  if (!RegisterMainWindowClass()) {
    MessageBox(NULL, TEXT("Error registering main window class."),
               TEXT("Error"), MB_ICONERROR | MB_OK);
    return 0;
  }

  /* Create our main window, or error */
  if (!(hWnd = CreateMainWindow())) {
    MessageBox(NULL, TEXT("Error creating main window."), TEXT("Error"),
               MB_ICONERROR | MB_OK);
    return 0;
  }

  /* Load accelerators */
  hAccelerators = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDR_ACCELERATOR));

  /* Show main window and force a paint */
  ShowWindow(hWnd, nCmdShow);
  UpdateWindow(hWnd);

  c_particle particle = c_particle(draw_pixel, fill_rect);
  /* Main message loop */
  while (msg.message != WM_QUIT) {
    if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      if (!TranslateAccelerator(hWnd, hAccelerators, &msg)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
      }
    }
    particle.draw();
  }

  return (int)msg.wParam;
}